package com.utsirc.activities;

import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.method.SingleLineTransformationMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.utsirc.R;
import com.utsirc.UTSirC;
import com.utsirc.irc.IRCService;

public class Main extends FragmentActivity implements OnClickListener {

	public static Main instance;

	public MainNavigationAdapter mAdapter;

	public EditText newChannelNameText;

	public void update() {
		this.mAdapter.notifyDataSetChanged();
	}

	/**
	 * 0 = channel list 1 = chat view
	 */
	public void showView(int view) {
		ViewPager mPager = (ViewPager) findViewById(R.id.pager);
		mPager.setCurrentItem(view);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		instance = this;
		super.onCreate(savedInstanceState);
		if (UTSirC.instance.currentUser == null) {
			Intent loginIntent = new Intent(this, ConnectActivity.class);
			startActivityForResult(loginIntent, 1);
		} else {
			createView();
		}
	}

	public void createView() {

		setContentView(R.layout.main);
		
		LinearLayout mainLayout = (LinearLayout)findViewById(R.id.background);
		mainLayout.setBackgroundResource(R.drawable.app_background);
		
		this.mAdapter = new MainNavigationAdapter(getSupportFragmentManager());
		ViewPager mPager = (ViewPager) findViewById(R.id.pager);
		mPager.setAdapter(mAdapter);
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {

		if (which == DialogInterface.BUTTON_POSITIVE) {
			String channelName = newChannelNameText.getText().toString()
					.replaceAll("\\W", "");
			if (channelName.length() > 0) {
				channelName = "#" + channelName.substring(0,Math.min(channelName.length(), 19));
				UTSirC.instance.addChannel(channelName);
				ChannelsFragment.instance.refresh();
			}
			dialog.dismiss();
		} else {
			dialog.cancel();
		}
	}

	public Builder getNewChannelDialog() {

		newChannelNameText = new EditText(this);
		newChannelNameText
				.setTransformationMethod(SingleLineTransformationMethod
						.getInstance());

		Builder build = new Builder(this).setTitle("New Channel")
				.setMessage("Enter the name for your new channel: ")
				.setView(newChannelNameText).setPositiveButton("Create", this)
				.setNegativeButton("Cancel", this);
		return build;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == 1) {

			if (resultCode == RESULT_OK) {

				// creating new user
				Log.d("onActivityResult", "RESULT_OK");
				createView();
			} else if (resultCode == RESULT_CANCELED) {
				// user clicked back :(
				Log.d("onActivityResult", "RESULT_CANCELED");
				finish();
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.action_logout:
			this.performLogout();
			break;
		case R.id.action_channel:
			showView(0);
			IRCService.client.listChannels();
			break;
		case R.id.action_new:
			getNewChannelDialog().show();
			break;
		default:
			return super.onOptionsItemSelected(item);
		}
		return true;
	}

	public void performLogout() {
		Log.d("performLogout", "performLogout");

		UTSirC.instance.logout();
		Intent loginIntent = new Intent(this, Main.class);
		loginIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(loginIntent);
		finish();
	}

	public static class MainNavigationAdapter extends FragmentPagerAdapter {

		public MainNavigationAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public int getCount() {

			if (UTSirC.instance.currentChannel == null) {
				return 1;
			} else {
				return 2;
			}
		}

		@Override
		public Fragment getItem(int position) {

			if (position == 0) {

				ChannelsFragment f = new ChannelsFragment();
				Bundle args = new Bundle();
				f.setArguments(args);
				return f;

			} else {

				ChatFragment fragments = new ChatFragment();

				Bundle args = new Bundle();
				args.putString("channel",
						UTSirC.instance.currentChannel.channelName);
				fragments.setArguments(args);

				return fragments;
			}
		}
	}
}
